#!/bin/bash
CG_NAME="test"
CG_BASE_DIR="/sys/fs/cgroup"

function build()
{
    make clean
    make
    return $?
}

function create_cgroup()
{
    if [ ! -d "${CG_BASE_DIR}" ]
    then
        echo "The folder does not exist.[${CG_BASE_DIR}]"
        exit 1
    fi
    mkdir -p ${CG_BASE_DIR}/memory/${CG_NAME}
    mkdir -p ${CG_BASE_DIR}/cpuset/${CG_NAME}
    mkdir -p ${CG_BASE_DIR}/cpu/${CG_NAME}
    return 0
}

function add_to_cg()
{
    local pid=0
    pid=$(ps -ef | grep test | grep -v grep | awk '{ print $2 }')
    [ -z "${pid}" ] && return 0
    echo "${pid}" > ${CG_BASE_DIR}/memory/${CG_NAME}/tasks
    echo "${pid}" > ${CG_BASE_DIR}/cpuset/${CG_NAME}/tasks
    echo "2" > ${CG_BASE_DIR}/cpuset/${CG_NAME}/cpuset.cpus
    echo "${pid}" > ${CG_BASE_DIR}/cpu/${CG_NAME}/tasks
    return 0
}

function kill_proc()
{
    local pid=0
    pid=$(ps -ef | grep test | grep -v grep | awk '{ print $2 }')
    [ -z "${pid}" ] && exit 0
    echo "pid=${pid}"
    kill -9 ${pid}
    ps -ef | grep test | grep -v grep
}

function get_mem_info()
{
    cat /proc/4069/status | grep -E "(VmRSS|VmSize)"
}

if [ "$1" = "k" ] || [ "$1" = "kill" ]
then
    kill_proc
    exit 0
fi

if [ "$1" = "m" ] || [ "$1" = "mem" ]
then
    get_mem_info
    exit 0
fi

if [ "$1" = "c" ] || [ "$1" = "cg" ]
then
    create_cgroup
    exit 0
fi

if [ "$1" = "a" ] || [ "$1" = "add" ]
then
    add_to_cg
    exit 0
fi

build
